package com.ccx.library.function.upload;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.function.Consumer;

/**
 * 文件上传工具
 */
public class UploadService {


    private final static String SUBFIX_FILE = "\\src\\main\\resources\\file\\";
    private final static String SUBFIX_EXCEL = "\\src\\main\\resources\\file\\export\\";
    private final static String SYSTEM_PATH = System.getProperty("user.dir");
    private final static Integer TYPE = 0;

    public static UploadVo Upload(Integer type,
                              MultipartFile file,
                              Consumer<UploadVo> consumer
                              ) {
        String filePath = SYSTEM_PATH + SUBFIX_FILE;
        String ExcelPath = SYSTEM_PATH + SUBFIX_EXCEL;
        String path = TYPE.equals(type) ? filePath : ExcelPath;
        String filename = UUID.randomUUID().toString();
        try {
            String Extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),
                    file.getOriginalFilename().length());
            file.transferTo(new File(path + filename + Extension));
            UploadVo uploadVo = new UploadVo()
                    .setSize(file.getSize())
                    .setFileName(filename+Extension)
                    .setAbPath(path+filename+Extension);
            consumer.accept(uploadVo);
            return uploadVo;
        } catch (IOException e) {
            e.printStackTrace();
            return new UploadVo();
        }
    }
}
